package com.financing.wap.util;


import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class WeChatRedirectTemplteUtil {
	
	/**
	 * 重定向地址
	 */
	public static String REDIRECT = "redirect";

	
	private static Map<String,Map<String,Object>> weChatRedirectTemplte = new HashMap<String,Map<String,Object>>();
	
	static{
		Logger logger = Logger.getLogger(WeChatRedirectTemplteUtil.class);
		
		SAXReader  saxReader = new SAXReader();
		try {
			Document document = saxReader.read(WeChatRedirectTemplteUtil.class.getResourceAsStream("/weChatRedirectTemplte.xml"));
			Element employees=document.getRootElement();   
			for(@SuppressWarnings("unchecked") Iterator<Element> typeElementIterator = employees.elementIterator();typeElementIterator.hasNext();){

					Element valueElement = typeElementIterator.next();
					
					String id = valueElement.attributeValue("code");
					Map<String,Object> messageMap = new HashMap<String,Object>();
					
					for(@SuppressWarnings("unchecked") Iterator<Element> valueElementIterator = valueElement.elementIterator();valueElementIterator.hasNext();){
						Element valuesElement = valueElementIterator.next();
						
						messageMap.put(valuesElement.getName(), valuesElement.getData());
					}
				weChatRedirectTemplte.put(id, messageMap);
			}
		} catch (DocumentException e) {
			logger.error("Init MessageTemplate error :", e);
			throw new RuntimeException(e);
		}
		
	}
	
	
	/**
	 * 
	* @Title: getMessage 
	* @Description: 获取信息内容
	* @param   type  信息类型
	* @param   id   类型下面的ID
	* @param   params  需要在模板中替换的动态内容
	* @return REDIRECT 
	* @throws
	 */
	public static String getWeChatRedirect(String id){
		if(StringUtils.isBlank(id)){
			return null;
		}
		
		Map<String,Object> typeMap = weChatRedirectTemplte.get(id);
		
		if(typeMap == null){
			return null;
		}
		
		String weChatRedirect = (String) typeMap.get(REDIRECT);
		
		return weChatRedirect;
	}

	
}
